﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LiteratureManage.Domain.DataAccess
{
    using Castle.Facilities.NHibernateIntegration;
    using Castle.Facilities.NHibernateIntegration.Components.Dao;
    using NHibernate;

    public class Dao<TKey, T> : NHibernateGenericDao, IDao<TKey, T> where T : class
    {
        public Dao(ISessionManager sessionManager)
            : base(sessionManager)
        {
        }

        public Dao(ISessionManager sessionManager, string sessionFactoryAlias)
            : base(sessionManager, sessionFactoryAlias)
        {
        }

        public virtual ISession OpenSession()
        {
            return base.SessionManager.OpenSession();
        }

        public virtual ISession OpenSession(string alias)
        {
            return base.SessionManager.OpenSession(alias);
        }

        #region IDao<TKey,T> Members

        public virtual TKey Create(T instance)
        {
            return (TKey)base.Create(instance);
        }

        public virtual void Delete(T instance)
        {
            base.Delete(instance);
        }

        public virtual void DeleteAll()
        {
            base.DeleteAll(typeof(T));
        }

        public virtual IList<T> GetAll()
        {
            return base.FindAll(typeof(T)).Cast<T>().ToList();
        }

        public virtual IList<T> GetAll(int firstRow, int maxRows)
        {
            return base.FindAll(typeof(T), firstRow, maxRows).Cast<T>().ToList();
        }

        public virtual T LoadById(TKey id, bool shouldLock)
        {
            using (var session = OpenSession())
            {
                T entity;

                if (shouldLock)
                {
                    entity = session.Load<T>(id, LockMode.Upgrade);
                }
                else
                {
                    entity = session.Load<T>(id);
                }

                return entity;
            }
        }

        public virtual T GetById(TKey id, bool shouldLock)
        {
            using (var session = OpenSession())
            {
                T entity;

                if (shouldLock)
                {
                    entity = session.Get<T>(id, LockMode.Upgrade);
                }
                else
                {
                    entity = session.Get<T>(id);
                }

                return entity;
            }
            //return (T)base.FindById(typeof(T), id);
        }

        public virtual void Save(T instance)
        {
            base.Save(instance);
        }

        public virtual void Update(T instance)
        {
            base.Update(instance);
        }

        #endregion
    }
}
